/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package webClient;

import java.io.IOException;
import webClient.HttpClient.SocketProcessor;

import engine.Singleton;
import figure.Cross;
import figure.Round;
import java.text.ParseException;
import java.util.List;
import java.util.logging.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import server.ConnectClient;
import tictactoe.BeforeGame;
import tictactoe.EndGame;
import tictactoe.Offer;
import tictactoe.SmallField;
import tictactoe.UserComman;
import tictactoe.noGame;


/**
 *
 * @author User
 */
public class WebClientReaction {
  private static SocketProcessor sok;
  private static WebConnectClient wc;
  
  public WebClientReaction(SocketProcessor sok)
  {
    this.sok = sok;
  }
  
  public void getString(String str) throws IOException, Throwable
  {
    if (str.indexOf("Submit=Connect") > 1) {
      System.out.println("start client server");
      connect(str);
    }
    if (str.indexOf("{\"Type\":") > 1) {
      str = str.replace("GET /?", "");
      str = str.replace(" HTTP/1.1", "");
      System.out.println(str);
      getClient(str);
    }
    if (str.indexOf("name") > 1) {
     // Singleton.sok.writeResponse(WebPages.list(Singleton.invite));
    }
    if (str.indexOf("list") > 1) {
      getPalyer(str);
    }
    
    if (str.indexOf("update") > 1) {
     // Singleton.sok.writeResponse(WebPages.update2(Singleton.status));
    }
    
    if (str.indexOf("play") > 1) {
      Singleton.sok.writeResponse(WebPages.startPlay());
    }
    if (str.indexOf("plaup") > 1) {
      Singleton.sok.writeResponse(WebPages.startPlay());
    }
    if (str.indexOf("reflis") > 1) {
      wc.refuse("{\"Type\":\"Refresh\"}");
    //  Singleton.sok.writeResponse(WebPages.startPlay());////////////////
    }
    
    if (str.indexOf("status") > 1) {
      Singleton.sok.writeResponse(WebPages.status());
    }
    if (str.indexOf("step") > 1) {
      addFigure(str);
      Singleton.sok.writeResponse(WebPages.startPlay());
    }
    if (str.indexOf("no") > 0) {
      Singleton.invite = "";
      String send = "{\"Type\":\"Refuse\", \"Name\":\"" + wc.getLogin() + "\"}";
      wc.refuse(send);
      Singleton.gameStatus = "Нет игры";
      Singleton.sok.writeResponse(WebPages.startPlay());
    }
    
    if (str.indexOf("yes") > 1) {
      Singleton.invite = "";
      String send = "{\"Type\":\"StartGame\", \"YouLogin\":\"" + wc.getLogin() + "\", \"PartnerLogin\":\"" + wc.getPartnerName() + "\"}";
      wc.refuse(send);
     Singleton.sok.writeResponse(WebPages.startPlay());
    }

  }
  
  private void addFigure(String str) {
    int end = str.indexOf("step");
    str  = str.substring(end + 4);
    end = str.indexOf(" ");
    str  = str.substring(0, end);
    String row = str.substring(0, 1);
    String col = str.substring(1);
    int r = Integer.parseInt(row);
    int c = Integer.parseInt(col);
    if (Singleton.sok.fig)
      Singleton.fig2[r][c] = 1;
    else
      Singleton.fig2[r][c] = 2;
    String send = "{\"Type\":\"Step\", \"Row\":\"" + row + "\", \"Col\":\"" + col + "\", \"Name\":\"" + wc.getLogin() + "\"}";
    wc.refuse(send);
    //block();
    Singleton.sok.steps[r][c] = true;
    Singleton.spaly = false;
   // Singleton.sok.step = false;
  }
  
    private static void block()
  {
    SmallField[][] matrix = Singleton.sok.matrix;
    for (int j=0; j<3; j++)
    {
      for (int i = 0; i < 3; i++) {
        SmallField now = matrix[j][i];
        now.setStep(false);
      }
    }
  }
  
  private void getPalyer(String str) throws Throwable
  {
    int end = str.indexOf("list");
    str  = str.substring(end + 5);
    end = str.indexOf(" ");
    str  = str.substring(0, end);
    Singleton.gameStatus = "Еще нет ответа от соперника";
    wc.setPlaer(str);
   // Singleton.sok.writeResponse(WebPages.update());
  }
  
  private static void connect(String str) throws IOException, Throwable
  {
    int end = str.indexOf("adrr=");
    str  = str.substring(end + 5);
    end = str.indexOf("&");
    String adrr = str.substring(0, end);
    
    str  = str.substring(end + 6);
    end = str.indexOf("&");
    String port = str.substring(0, end);
    
    str  = str.substring(end + 7);
    end = str.indexOf("&");
    String login = str.substring(0, end);
    
    int por = Integer.parseInt(port);
    
    System.out.println(adrr + " " + port + " " + login);
    wc = new WebConnectClient(por, login, adrr, sok); // закоментены порты записано хард кодом в WebConnectClient
    sok.setWc(wc);
    Singleton.sok.writeResponse(WebPages.listOfPlaer());
    //sok.writeResponse(WebPages.listOfPlaer());
    //wc.setSok(sok);
  }
  
  public void getClient(String str) throws org.json.simple.parser.ParseException, Throwable
   {
       String type;
       JSONParser parser = new JSONParser();
       Object obj = parser.parse(str);
       JSONObject jsonObj = (JSONObject) obj;
       
       type = (String) jsonObj.get("Type");
       
       if (type.equals("Users"))
       {
         //         JSONObject jsonObserv = (JSONObject)jsonObj.get("Data");
         String name = (String) jsonObj.get("Name");
         System.out.println(name + "Это что соко");
         addUser(name);
       }
       
       if (type.equals("Offer"))
       {
         String name = (String) jsonObj.get("Name");
         offerUser(name);
       }
       
       if (type.equals("NoGame"))
       {
         Singleton.gameStatus = "Вам отказано";
       }
       
       if (type.equals("StartGame"))
       {
         String figure = (String) jsonObj.get("Figure");
         String step = (String) jsonObj.get("Step");
        // Singleton.status = "Вы ходите:" + step + " ваша фигура: " + figure + "<h2> <a href=\"play\">Начать игру</a> </h2>";
         startGame(figure, step);
       }
       
       if (type.equals("Step"))
       {
         String row = (String) jsonObj.get("Row");
         String col = (String) jsonObj.get("Col");
         partnerStep(row, col);
       }
       
       if (type.equals("Finish"))
       {
         String status = (String) jsonObj.get("Status");
         finishGame(status);
       }

   }
    
    public void finishGame(String status)
    {
      String end = "1";
      if (status.equals("win"))
        end = "Победил!";
      if (status.equals("lose"))
        end = "Проиграл!";
      if (status.equals("eq"))
        end = "Ничья!";
      
      Singleton.gameStatus = "Ты: " + end;
      Singleton.status = "<meta HTTP-EQUIV=\"Refresh\" Content=\"1; URL=http://localhost:7777/update\">"
          + "<html><body><h2>Еще нет ответа</h2>"
          + "</body></html>";
    //new EndGame(end).setVisible(true);
    //UserComman.clearField();
      clearField();
    }
    
    private void clearField()
    {
      for (int j = 0; j < 3; j++)
      {
        for (int i = 0; i < 3; i++)
        {
          Singleton.fig2[j][i] = 0;
        }
      }
    }
    
    public void partnerStep(String row, String col)
    {
      int r = Integer.parseInt(row);
      int c = Integer.parseInt(col);
      Singleton.sok.steps[r][c] = true;
      SmallField now = Singleton.sok.matrix[r][c];
       
        Singleton.sok.step = true;
      
      if (Singleton.sok.fig) {
        Singleton.fig2[r][c] = 2;
      } else {
        Singleton.fig2[r][c] = 1;
      }
      Singleton.spaly = true;
     //disblock();
      
    }
    
    public static void disblock() {
    for (int j=0; j<3; j++)
    {
      for (int i = 0; i < 3; i++) {
        SmallField now = Singleton.sok.matrix[j][i];
        if (!Singleton.sok.steps[j][i]){
          now.setStep(true);
        }
      }
    }
  }
    
    public void startGame(String figure, String step)
    {
      boolean fig = false;
      boolean fstep = false;
      Singleton.spaly = false;
      if(figure.equals("Cross"))
        fig = true;
      if(step.equals("First")){
        fstep = true;
        Singleton.spaly = true;
      }  
      play(fig, fstep);
      Singleton.sok.fig = fig;
     // Singleton.sok.step = fstep;
      Singleton.gameStatus = "Ваша фигура "+ figure +" ваш ход " + step + "!";
//      Singleton.status = "<meta HTTP-EQUIV=\"Refresh\" Content=\"1; URL=http://localhost:7777/update\">"
//          + "<html><body><h2>Еще нет ответа</h2>"
//          + "</body></html>";
     // new BeforeGame(fig, fstep).setVisible(true);
    }
    
    public static void play(boolean figure, boolean step)
  {
    Singleton.sok.fig = figure;
   // Singleton.sok.step = step;
    for (int j=0; j<3; j++)
    {
      for (int i = 0; i < 3; i++) {
        SmallField field = new SmallField(j, i, figure, step);
        Singleton.sok.matrix[j][i] = field;
      }
    }
    if(Singleton.sok.step){
     // disblock();
    }
      
  }
    
    public void noGame()
    {
      new noGame().setVisible(true);
    }
    
    public void offerUser(String name)
    {
      Singleton.gameStatus = "Вас приглашает " + name + "Играть? <a href=\"yes\">Да</a> <a href=\"no\">Нет</a>";
      wc.setPartner(name);
    }
    
    public void addUser(String name) throws Throwable
    {
      Singleton.Clientusers.clear();
      while (name.length() > 1)
      {
        int end = name.indexOf("-");
        String na = "";
        if (end > 0)
        {
          na = name.substring(0, end);
          name = name.substring(end + 1);
        } else
        {
          na = name;
          name = "";
        }
        Singleton.Clientusers.add(na);
        System.out.println("hh" + na);
      }
    }

  
  
}
